package com.wxmit.ot.handler.type;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * StringLinkedHashMapTypeHandler
 *
 * @author huangxiong
 * @version V1.0
 * @date 2023/2/23 08:54
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Map.class)
@Slf4j
public class StringLinkedHashMapTypeHandler implements TypeHandler<Map<String,String>>  {
    private static final String COMMA = ",";

    @Override
    public void setParameter(PreparedStatement ps, int i, Map<String,String> strings, JdbcType jdbcType) throws SQLException {
        // 设置占位符
        ObjectMapper mapper = new ObjectMapper();
        try {
            ps.setString(i,mapper.writeValueAsString(strings));
        } catch (JsonProcessingException e) {
            log.error("Json 格式化转换时出现异常: map to string ::: map is 【 $strings 】 ",e);
            ps.setString(i,null);
        }
    }

    @Override
    public Map<String,String> getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return getResult(value);
    }

    @Override
    public Map<String,String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return getResult(value);
    }

    @Override
    public Map<String,String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return getResult(value);
    }

    private Map<String,String> getResult(String value) {
        if (value.isNullOrBlank()) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
           return mapper.readValue(value, LinkedHashMap.class);
        } catch (JsonProcessingException e) {
           log.error("Json 格式化转换时出现异常: string to map ::: string is 【 $value 】 ",e);
           return null;
        }
    }

}
